#include "custom_nvs.h"
#include <stdio.h>
#include "esp_flash.h"
#include "esp_partition.h"
#include "esp_flash_encrypt.h"
#include "nvs_flash.h"
#define CUSTOM_NVS_PART_NAME "custom_nvs"
static char * dap_setting = "dap_settings";
static char *ui_setting = "ui_settings";
static bool initialized = false;

static esp_err_t custom_nvs_part_init(const char *name)
{
    /*不加密分区*/
    return nvs_flash_init_partition(name);
}

esp_err_t custom_nvs_init(void)
{
    esp_err_t ret;
    /* Initialize the custom NVS partition */
    ret = custom_nvs_part_init(CUSTOM_NVS_PART_NAME);
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase_partition(CUSTOM_NVS_PART_NAME));
        ret = custom_nvs_part_init(CUSTOM_NVS_PART_NAME);
    }
    ESP_ERROR_CHECK(ret);
    initialized = true;

    return ret;
}

esp_err_t custom_nvs_write(custom_nvs_key_t key, const void *value, size_t len)
{
    if (initialized==false)
        return ESP_ERR_NOT_SUPPORTED;
    char *key_str = NULL;
    switch (key) {
        case DAP_SETTING:
            key_str = dap_setting;
            break;
        case UI_SETTING:
            key_str = ui_setting;
            break;
        default:
            return ESP_FAIL;
    }
    esp_err_t ret;
    nvs_handle my_handle;
    ret = nvs_open_from_partition(CUSTOM_NVS_PART_NAME, key_str, NVS_READWRITE, &my_handle);
    if (ret != ESP_OK) {
        return ret;
    }
    ret = nvs_set_blob(my_handle, key_str, value, len);
    nvs_commit(my_handle);
    nvs_close(my_handle);
    return ret;
}

esp_err_t custom_nvs_read(custom_nvs_key_t key, void *value, size_t max_len)
{
    if (initialized == false)
        return ESP_ERR_NOT_SUPPORTED;
    char *key_str = NULL;
    switch (key) {
        case DAP_SETTING:
            key_str = dap_setting;
            break;
        case UI_SETTING:
            key_str = ui_setting;
            break;
        default:
            return ESP_FAIL;
    }
    esp_err_t ret;
    size_t exist_len = 0;
    nvs_handle my_handle;
    ret = nvs_open_from_partition(CUSTOM_NVS_PART_NAME, key_str, NVS_READONLY, &my_handle);
    nvs_get_blob(my_handle, key_str, NULL, &exist_len);
    if (exist_len > max_len)
        return ESP_FAIL;
    nvs_get_blob(my_handle, key_str, value, &exist_len);

    nvs_close(my_handle);
    return ret;
}